#include "Player.h"

#include <SFML/Graphics/Color.hpp>

#include "DummyWeapon.h"

using namespace mega;


Player::Player()
	: m_shape(20.f)
	, m_velocity(0.5f)
	, m_weapon(new DummyWeapon)
{
	// set origin to the center of circle
	m_shape.setOrigin(m_shape.getRadius() / 2, m_shape.getRadius() / 2);
	m_shape.setFillColor(sf::Color(100, 255, 150));
}


Player::Player(const Player & _rhs)
	: m_shape(_rhs.m_shape)
	, m_velocity(_rhs.m_velocity)
	, m_weapon(new DummyWeapon)
{
	*m_weapon = *_rhs.m_weapon;
}


Player & Player::operator=(const Player & _rhs)
{
	m_shape = _rhs.m_shape;
	m_velocity = _rhs.m_velocity;

	delete m_weapon;
	m_weapon = new DummyWeapon(*_rhs.m_weapon);

	return *this;
}


Player::~Player()
{
	delete m_weapon;
}


void Player::updateState()
{
	if (m_moving.right)
		move(Position(m_velocity, 0.));

	if (m_moving.left)
		move(Position(-m_velocity, 0.));

	if (m_moving.up)
		move(Position(0., -m_velocity));

	if (m_moving.down)
		move(Position(0., m_velocity));

	m_weapon->updateState();
}


void Player::render(RenderTarget & _target)
{
	updateState();
	
	_target.draw(m_shape);

	m_weapon->render(_target);
}


void Player::move(const Position & _offset)
{
	GameObject::move(_offset);

	m_shape.move(_offset);
	m_weapon->move(_offset);
}


void Player::shoot(const Position & _direction)
{
	m_weapon->createBullet(_direction);
}


bool Player::onKeyPressed(const sf::Keyboard::Key & _key)
{
	using sf::Keyboard;

	bool isHandled = false;
	
	if (Keyboard::D == _key)
	{
		m_moving.right = true;
		isHandled      = true;
	}

	if (Keyboard::A == _key)
	{
		m_moving.left = true;
		isHandled     = true;
	}

	if (Keyboard::W == _key)
	{
		m_moving.up = true;
		isHandled   = true;
	}

	if (Keyboard::S == _key)
	{
		m_moving.down = true;
		isHandled     = true;
	}
	
	return isHandled;
}


bool Player::onKeyReleased(const sf::Keyboard::Key & _key)
{
	using sf::Keyboard;

	bool isHandled = false;

	MovingDirections wasMoving = m_moving;

	if (Keyboard::D == _key)
	{
		m_moving.right = false;
		isHandled      = true;
	}

	if (Keyboard::A == _key)
	{
		m_moving.left = false;
		isHandled     = true;
	}

	if (Keyboard::W == _key)
	{
		m_moving.up = false;
		isHandled   = true;
	}

	if (Keyboard::S == _key)
	{
		m_moving.down = false;
		isHandled     = true;
	}

	return isHandled;
}


bool Player::onMousePressed(const sf::Mouse::Button & _button, const Position & _pos)
{
	// TODO: provide clever shooting

	return false;
}


bool Player::onMouseReleased(const sf::Mouse::Button & _button, const Position & _pos)
{
	using sf::Mouse;

	if (Mouse::Left == _button)
		m_weapon->createBullet(_pos);

	return true;
}
